package com.gitee.cashzhang.test.basic.method;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;

/**
 * @author Cash Zhang
 * @version v1.0
 * @since 2019/05/17 17:16
 */
public class New implements Cloneable , Serializable {

  private static final long serialVersionUID = 1346773028601559058L;

  @Override
  protected Object clone() throws CloneNotSupportedException {
    return super.clone();
  }

  public static void main(String[] args) throws Exception {
    // 1、使用new关键字
    New new1 = new New();
    // 2、使用 Class 类的 newInstance() 方法
    New new21 = (New) Class.forName("com.gitee.cashzhang27.test.method.New").newInstance();
    New new22 = New.class.newInstance();
    // 3、使用 Constructor 类的 newInstance() 方法
    Constructor<New> constructor = New.class.getConstructor();
    New new3 = constructor.newInstance();
    // 4、使用 clone 方法，必须实现 Cloneable 接口，并实现其定义的 clone 方法
    New new4 = (New)new3.clone();
    // 5、通过对象流，必须实现Serializable
    String path = New.class.getClassLoader().getResource("").getPath();
    String objectFilePath = path + "out.txt";

    ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(objectFilePath));
    objectOutputStream.writeObject(new1);

    ObjectInput objectInput = new ObjectInputStream(new FileInputStream(objectFilePath));
    New new5 = (New) objectInput.readObject();
  }
}
